# name : BE (HVD) analysis using proc mixed with 4-way design 2x4
# key : be.hvd.mixed.4way.
# contributor: Shuguang Sun
# --
* Dataset containing TEST observations;
data test1;
set pk;
if trt = 'T';
if (seq = 1 and per = 1) or (seq = 2 and per = 2);
lat1t = lauct;
run;

data test2;
set pk;
if trt = 'T';
if (seq = 1 and per = 3) or (seq = 2 and per = 4);
lat2t = lauct;
run;

* Dataset containing REFERENCE observations;
data ref1;
set pk;
if trt = 'R';
if (seq = 1 and per = 2) or (seq = 2 and per = 1);
lat1r = lauct;
run;

data ref2;
set pk;
if trt = 'R';
if (seq = 1 and per = 4) or (seq = 2 and per = 3);
lat2r = lauct;
run;

* Determine Iij and Dij;
data scavbe;
merge test1 test2 ref1 ref2;
by seq subj;
ilat = 0.5 * (lat1t + lat2t - lat1r - lat2r);
dlat = lat1r - lat2r;
run;

* Intermediate analysis -- ilat;
proc mixed data=scavbe;
class seq;
model ilat = seq / clparm alpha=0.1;
estimate 'average' intercept 1 seq 0.5 0.5 / e cl alpha=0.1;
ods output overallanova=iout1;
ods output Estimates=iout2;
ods output NObs=iout3;
title1 'scaled average BE';
title2 'intermediate analysi - ilat, mixed';
run;

* From the dataset IOUT2, calculate the following IOUT2;
data iout2;
set iout2;
pointest = exp(estimate);
x = estimate**2 - stderr**2;
boundx = (max((abs(LowerCL)), (abs(UpperCL))))**2;
run;

* Intermediate analysis -- dlat;
proc mixed data=scavbe;
class seq;
model dlat = seq;
estimate 'average' intercept 1 seq 0.5 0.5 / e cl alpha=0.1;
ods output overallanova=dout1;
ods output Estimates=dout2;
ods output NObs=dout3;
title1 'scaled average BE';
title2 'intermediate analysis - dlat, mixed';
run;

* From the dataset DOUT1, calculate the following DOUT1;
data dout1;
set dout1;
s2wr = ms / 2;
run;

data dout2;
set dout2;
dfd = df;
run;

* From the above parameters, calculate the final 95 % upper confidence bound;
data result;
merge iout2 dout1 dout2;
theta = ((log(1.25)) / 0.25)**2;
y = - theta * s2wr;
boundy = y * dfd / cinv(0.95, dfd);
sWR = sqrt(s2wr);
critbound = (x + y) + sqrt(((boundx - x)**2) + ((boundy - y)**2));
run;